package edu.usc.libtalk.task;

import org.json.JSONObject;
import edu.usc.libtalk.utils.ApplicationService;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;

public class GetJSONObjectTask extends AsyncTask<String, Integer, JSONObject> {

	private static final String TAG = "GetJSONObjectTask";	
	private ProgressBar progressbar;
	private int percent;
	
	public GetJSONObjectTask withProgressBar(ProgressBar progressbar, int percent){
		this.progressbar = progressbar;
		this.percent = percent;
		return this;
	}	
	
	private int lastProgressUpdate = 0;
	@Override
	protected void onProgressUpdate(Integer... changed) {
		if(progressbar != null){
			double scaledChange = (changed[0] - lastProgressUpdate) * percent / 100.0;
			synchronized (progressbar) {
				progressbar.setProgress(progressbar.getProgress() + (int)scaledChange);
			}
			lastProgressUpdate = changed[0];
		}
	}	
	
	@Override
	protected JSONObject doInBackground(String... urls) {
		
		if (urls.length == 0 || urls[0] == null)
			return null;
		JSONObject result = null;
		String url = urls[0];
				
		try {
			publishProgress(30);
			String httpget_result = ApplicationService.executeHttpGet(url);
			
			publishProgress(90);
			result = new JSONObject(httpget_result);
			
		} catch (Exception e) {
			Log.e(TAG, "doInBackground: " + e.toString());
			return null;
		}
		
		publishProgress(100);		
		return result;
	}		
}
